<?php
/*
 * Redis访问频率控制
 * @package
 * @author     wanglei@wyzc.com
 * @version    $Id$
 */

$redis = new Redis();
$redis->connect('114.215.124.216', 6379);

$ip = $_SERVER['REMOTE_ADDR'];

$limit = false;
$hkey  = $ip . '_access_limit';

if (!$redis->hGet($hkey, 'start_time')) {
	//初始化
	$redis->hSet($hkey, 'start_time', time());
	$redis->hSet($hkey, 'limit_num', 1);
}else{
	//每次访问次数+1
	$redis->hIncrBy($hkey, 'limit_num', 1);
};

//访问开始时间
$access_star_time = $redis->hGet($hkey, 'start_time');
//访问次数
$access_limit_num  = $redis->hGet($hkey, 'limit_num');

$time = time() - $access_star_time;

if ($time <= 60) {
	if ($access_limit_num > 10) {
		//如果60秒以内访问超过10次
		$limit = true;
	}
} else {
	//如果大于60秒，重置访问时间与次数
	$redis->hSet($hkey, 'start_time', time());
	$redis->hSet($hkey, 'limit_num', 1);
	$access_limit_num = 1;
}

echo $time.'<br/>';
if ($limit) {
	echo 'access failed';
} else {
	echo 'access success ' . $access_limit_num;
}


